package controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

import db.DbConn;

public class AjaxServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	DbConn conn;

	@Override
	public void init() throws ServletException {
		conn = new DbConn();
		conn.setDbUrl(getServletContext().getInitParameter("dbUrl"));
		conn.setDbUser(getServletContext().getInitParameter("dbUser"));
		conn.setDbPass(getServletContext().getInitParameter("dbPass"));
	}

	@SuppressWarnings("unchecked")
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		if (req.getParameter("checkId") != null) {
			JSONObject json = new JSONObject();
			String userId = req.getParameter("checkId");
			boolean checkId = conn.checkUser(userId);
			int dupFlag = checkId ? 1 : 0;
			json.put("check", dupFlag);
			resp.setContentType("application/json");
			PrintWriter out = resp.getWriter();
			out.print(json);
			out.flush();
		} else if(req.getParameter("oldProjectId") != null) {
			//userId 와 oldProjectId 로 히스토리를 가져온다. 
			JSONArray json = new JSONArray();
			String oldProjectId = (String)req.getParameter("oldProjectId");
			boolean isOldProject = Boolean.parseBoolean((String)req.getParameter("isOldProject"));
			int completecnt = Integer.parseInt((String)req.getParameter("completecnt"));
			String userId = (String) req.getSession().getAttribute("userId");
			if(isOldProject == false )
				json = conn.getDataFromCurrentProject(userId, oldProjectId);
			else
				json = conn.getDataFromOldProject(userId, oldProjectId,completecnt);
			
			resp.setCharacterEncoding("UTF-8");
			resp.setContentType("application/json");
			PrintWriter out = resp.getWriter();
			out.print(json);
			out.flush();
		} else if (req.getParameter("isexpired") != null) {
			JSONArray json = new JSONArray();
			json = conn.getProjectStatus((String)req.getSession().getAttribute("userId"));
			resp.setCharacterEncoding("UTF-8");
			resp.setContentType("application/json");
			PrintWriter out = resp.getWriter();
			out.print(json);
			out.flush();
		} else if(null != req.getParameter("checkoauth")){
			String userid = (String)req.getSession().getAttribute("userId");
			if(!"".equals(userid)) {
				String oauthtoken = conn.getAccessToken(userid);
				JSONObject json = new JSONObject();
				json.put("token", oauthtoken);
				resp.setCharacterEncoding("UTF-8");
				resp.setContentType("application/json");
				PrintWriter out = resp.getWriter();
				out.print(json);
				out.flush();
			}
		}
	}
}
